﻿using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using Common;
using Common.Widget;
using WidgetApplication._WGRUS_WidgetTableAdapters;

namespace WidgetApplication
{
    public class InventoryRequestHandler
    {
        private QueueHandler queueHandler;

        public InventoryRequestHandler(QueueHandler queueHandler)
        {
            this.queueHandler = queueHandler;
            queueHandler.MessageReceived += queueHandler_MessageReceived;
        }

        private void queueHandler_MessageReceived(object sender, MessageReceivedEventArgs e)
        {
            InventoryResType inventoryResponse = null;
            try
            {
                //To Class
                XmlSerializer xmlSerializer = new XmlSerializer(typeof (InventoryReqType));
                InventoryReqType inventoryRequest =
                    (InventoryReqType) xmlSerializer.Deserialize(e.Message.CreateReader());

                inventoryResponse = new InventoryResType();
                inventoryResponse.ItemId = inventoryRequest.ItemId;

                //Load database
                ItemTableAdapter adapter = new ItemTableAdapter();
                _WGRUS_Widget db = new _WGRUS_Widget();
                _WGRUS_Widget.ItemDataTable table = adapter.GetDataByItemId(inventoryRequest.ItemId);


                if (table.Count < 1)
                {
                    inventoryResponse.InStock = false;
                }
                else
                {
                    _WGRUS_Widget.ItemRow item = table[0];

                    //Check inventory

                    if (item.StockAmount - inventoryRequest.Quantity >= 0)
                    {
                        inventoryResponse.InStock = true;
                        item.StockAmount = item.StockAmount - inventoryRequest.Quantity;
                        adapter.Update(item);
                    }
                    else
                    {
                        inventoryResponse.InStock = false;
                    }
                }
            }
            catch (Exception)
            {
                inventoryResponse = new InventoryResType
                {
                    InStock = false,
                    ItemId = "-1"
                };
            }
            var sw = new StringWriter();
            var xmlSer = new XmlSerializer(typeof (InventoryResType));
            var noNamespaces = new XmlSerializerNamespaces();
            noNamespaces.Add("", "");
            xmlSer.Serialize(sw, inventoryResponse); //, noNamespaces);

            queueHandler.SendMessage(Constants.WIDGET_INVENTORY_RESPONSE_QUEUE, sw.ToString(), e.Properties);
        }
    }
}